package com.ruoyi.business.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.S7VariablesConfig;
import com.ruoyi.business.service.IS7VariablesConfigService;
import com.ruoyi.business.service.S7VariableManagerService;
import com.ruoyi.business.service.s7.S7ConnectionManagerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * S7协议变量配置Controller
 * 
 * @author qiancheng
 * @date 2025-08-30
 */
@Api(tags = "S7协议变量配置")
@RestController
@RequestMapping("/business/config")
public class S7VariablesConfigController extends BaseController
{
    @Autowired
    private IS7VariablesConfigService s7VariablesConfigService;

    @Autowired
    private S7VariableManagerService s7VariableManagerService;

    @Autowired
    private S7ConnectionManagerService s7ConnectionManagerService;

    /**
     * 查询S7协议变量配置列表
     */
    @ApiOperation("查询S7协议变量配置列表")
    @PreAuthorize("@ss.hasPermi('business:config:list')")
    @GetMapping("/list")
    public TableDataInfo list(S7VariablesConfig s7VariablesConfig)
    {
        startPage();
        List<S7VariablesConfig> list = s7VariablesConfigService.selectS7VariablesConfigList(s7VariablesConfig);
        return getDataTable(list);
    }

    /**
     * 导出S7协议变量配置列表
     */
    @ApiOperation("导出S7协议变量配置列表")
    @PreAuthorize("@ss.hasPermi('business:config:export')")
    @Log(title = "S7协议变量配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, S7VariablesConfig s7VariablesConfig)
    {
        List<S7VariablesConfig> list = s7VariablesConfigService.selectS7VariablesConfigList(s7VariablesConfig);
        ExcelUtil<S7VariablesConfig> util = new ExcelUtil<S7VariablesConfig>(S7VariablesConfig.class);
        util.exportExcel(response, list, "S7协议变量配置数据");
    }

    /**
     * 获取S7协议变量配置详细信息
     */
    @ApiOperation("获取S7协议变量配置详细信息")
    @PreAuthorize("@ss.hasPermi('business:config:query')")
    @GetMapping(value = "/{variableId}")
    public AjaxResult getInfo(@ApiParam("变量ID") @PathVariable("variableId") Long variableId)
    {
        return success(s7VariablesConfigService.selectS7VariablesConfigByVariableId(variableId));
    }

    /**
     * 新增S7协议变量配置
     */
    @ApiOperation("新增S7协议变量配置")
    @PreAuthorize("@ss.hasPermi('business:config:add')")
    @Log(title = "S7协议变量配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@ApiParam("S7变量配置信息") @RequestBody S7VariablesConfig s7VariablesConfig)
    {
        return toAjax(s7VariablesConfigService.insertS7VariablesConfig(s7VariablesConfig));
    }

    /**
     * 修改S7协议变量配置
     */
    @ApiOperation("修改S7协议变量配置")
    @PreAuthorize("@ss.hasPermi('business:config:edit')")
    @Log(title = "S7协议变量配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@ApiParam("S7变量配置信息") @RequestBody S7VariablesConfig s7VariablesConfig)
    {
        return toAjax(s7VariablesConfigService.updateS7VariablesConfig(s7VariablesConfig));
    }

    /**
     * 删除S7协议变量配置
     */
    @ApiOperation("删除S7协议变量配置")
    @PreAuthorize("@ss.hasPermi('business:config:remove')")
    @Log(title = "S7协议变量配置", businessType = BusinessType.DELETE)
	@DeleteMapping("/{variableIds}")
    public AjaxResult remove(@ApiParam("变量ID数组") @PathVariable Long[] variableIds)
    {
        return toAjax(s7VariablesConfigService.deleteS7VariablesConfigByVariableIds(variableIds));
    }

    /**
     * 获取S7变量缓存统计信息
     */
    @ApiOperation("获取S7变量缓存统计信息")
    @PreAuthorize("@ss.hasPermi('business:config:query')")
    @GetMapping("/cache/statistics")
    public AjaxResult getCacheStatistics()
    {
        return success(s7VariableManagerService.getCacheStatistics());
    }

    /**
     * 重新加载S7变量配置
     */
    @ApiOperation("重新加载S7变量配置")
    @PreAuthorize("@ss.hasPermi('business:config:edit')")
    @Log(title = "S7变量配置", businessType = BusinessType.UPDATE)
    @PostMapping("/reload")
    public AjaxResult reloadVariables()
    {
        try {
            s7VariableManagerService.reloadVariables();
            return success("变量配置重新加载成功");
        } catch (Exception e) {
            return error("重新加载失败：" + e.getMessage());
        }
    }

    /**
     * 获取所有PLC连接状态
     */
    @ApiOperation("获取所有PLC连接状态")
    @PreAuthorize("@ss.hasPermi('business:config:query')")
    @GetMapping("/connection/status")
    public AjaxResult getConnectionStatus()
    {
        // 创建一个包含所有PLC连接状态的映射
        Map<String, Boolean> statusMap = new HashMap<>();
        List<String> plcIps = s7VariableManagerService.getAllPlcIps();
        
        for (String plcIp : plcIps) {
            statusMap.put(plcIp, s7ConnectionManagerService.isConnected(plcIp));
        }
        
        return success(statusMap);
    }

    /**
     * 初始化指定PLC连接
     */
    @ApiOperation("初始化指定PLC连接")
    @PreAuthorize("@ss.hasPermi('business:config:edit')")
    @Log(title = "S7PLC连接", businessType = BusinessType.UPDATE)
    @PostMapping("/connection/init/{plcIp}")
    public AjaxResult initConnection(@ApiParam("PLC IP地址") @PathVariable String plcIp)
    {
        try {
            // 检查PLC是否有激活的变量配置
            if (!s7VariableManagerService.hasActiveVariables(plcIp)) {
                return error("PLC [" + plcIp + "] 没有配置激活的变量");
            }
            
            // 获取PLC的变量配置
            List<S7VariablesConfig> variables = s7VariableManagerService.getVariablesByPlcIp(plcIp);
            
            // 初始化连接池
            boolean success = s7ConnectionManagerService.initializeConnection(plcIp, variables);
            if (success) {
                return success("PLC [" + plcIp + "] 连接初始化成功");
            } else {
                return error("PLC [" + plcIp + "] 连接初始化失败");
            }
        } catch (Exception e) {
            return error("初始化连接失败：" + e.getMessage());
        }
    }
}